from sqlalchemy import Column, Integer, String, DateTime, func, SmallInteger, Float
from sqlalchemy.sql.schema import ForeignKey
from .base import db
from ..error import InvalidUsage


class Application(db.Model):
    __tablename__ = 'applications'
    id = Column(Integer, nullable=False, primary_key=True)
    description = Column(String(200), nullable=False)
    state = Column(SmallInteger, nullable=False, default=0)
    created = Column(DateTime, server_default=func.now(), comment='创建时间')
    updated = Column(DateTime, server_default=func.now(),
                     onupdate=func.now(), comment='修改时间')
    score = Column(Float, nullable=True)

    applier_id = Column(Integer, ForeignKey('users.id'))

    mission_id = Column(Integer, ForeignKey('missions.id'))

    def save(self):
        db.session.add(self)
        db.session.commit()

    @staticmethod
    def delete_app(app):
        if app.state != 0:
            raise InvalidUsage('Application has been proceed', 400)
        db.session.delete(app)
        db.session.commit()

    @staticmethod
    def query_by_id(identify):
        return Application.query.filter_by(id=identify).one_or_none()

    @staticmethod
    def update_by_id(identify, args: dict):
        Application.query.filter_by(id=identify).update(args)
        db.session.commit()
        return Application.query_by_id(identify)

    @staticmethod
    def query_by_mission_id_and_user_id(mission_id, user_id):
        return Application.query.filter_by(mission_id=mission_id, applier_id=user_id).one_or_none()
